package com.zhangsr.mongodb.client.util;

import com.mongodb.DBObject;
import com.mongodb.MongoException;
import com.zhangsr.mongodb.client.constants.MongoConstants;
import net.vz.mongodb.jackson.MongoJsonMappingException;
import net.vz.mongodb.jackson.internal.object.BsonObjectGenerator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;

/**
 * @Author: zhangsr
 */
public class ConverterUtil {

    public static final Log logger = LogFactory.getLog(MongoConstants.COMMON_MONGO);

    public static <E> DBObject convertToDbObject(E object, ObjectMapper objectMapper) {
        if (object == null) {
            return null;
        }
        BsonObjectGenerator generator = new BsonObjectGenerator();
        try {
            objectMapper.writeValue(generator, object);
        } catch (JsonMappingException e) {
            logger.error("类型转换异常" + e);
            throw new MongoJsonMappingException(e);
        } catch (IOException e) {
            // This shouldn't happen
            throw new MongoException("Unknown error occurred converting BSON to object", e);
        }
        return generator.getDBObject();
    }

}
